import React from 'react';
import { Button, Form, Input, message } from 'antd';
import { getlogin } from '../../reques';
import {useNavigate} from 'react-router-dom'

const Index = () => {
//  const [messageApi, contextHolder] = message.useMessage()
const navigate=useNavigate()
  const onFinish = (values) => {
    console.log('Success:', values);
    
    let data = {
      username: values.username,
      password: values.password
    }
    getlogin(data).then((res) => {
      // console.log(res)
      let {data:{code,msg,token,username,userId,auth}}=res
      if (code === 200) {
        // alert('登录成功')
        // window.location.href='/#/home'
       message.success(msg, 2.5,()=>{
        navigate('/')
        sessionStorage.setItem('token',token)
        sessionStorage.setItem('username',JSON.stringify(username))
        sessionStorage.setItem('userId',userId)
        sessionStorage.setItem('auth',JSON.stringify(auth))
       })
      }else{
        message.error(msg, 2.5)
      }
    })
  };
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
  return (
    <div>
      <Form
        name="basic"
        labelCol={{
          span: 8,
        }}
        wrapperCol={{
          span: 16,
        }}
        style={{
          maxWidth: 600,
        }}
        initialValues={{
          remember: true,
        }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item
          label="用户"
          name="username"
          rules={[
            {
              required: true,
              message: 'Please input your username!',
            },
            {
              pattern: /^[a-zA-Z]{2,10}$/, message: "账号必须是2~10位的字母" 
            }
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="密码"
          name="password"
          rules={[
            {
              required: true,
              message: 'Please input your password!',
            },
          ]}
        >
          <Input.Password />
        </Form.Item>


        <Form.Item
          wrapperCol={{
            offset: 8,
            span: 16,
          }}
        >
          <Button type="primary" htmlType="submit">
            登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  )
}
export default Index;